const XLSX = require('xlsx');
const fs = require('fs');

function matchItemList(rowData, conditionMapList, uniqueMap) {
    for (let conditionMap of conditionMapList) {
        let name = conditionMap["name"];
        let itemValue = rowData[name];

        let operator = conditionMap["operator"];
        let value = conditionMap["value"];
        if (operator == "required") {
            if (!itemValue) {
                return false;
            }
        } else if (operator == "unique") {
            let uniqueList = uniqueMap[name];
            if (!uniqueList) {
                uniqueList = [];
                uniqueMap[name] = uniqueList;
            }
            if (uniqueList.includes(itemValue)) {
                return false;
            } else {
                uniqueList.push(itemValue);
            }


        } else if (operator == "range") {
            let numberValue = itemValue; // 将字符串转换为 double
            let valueArray = value.split(",");
            let min = parseFloat(valueArray[0]);
            let max = parseFloat(valueArray[1]);
            if (!isNaN(min)) {
                if (numberValue < min) {
                    return false;
                }
            }
            if (!isNaN(max)) {
                if (numberValue > max) {
                    return false;
                }
            }
        } else if (operator == "equals") {
            if (value.toString() != itemValue.toString()) {
                return false;
            }

        } else if (operator == "not") {
            if (value.toString() == itemValue.toString()) {
                return false;
            }
        } else if (operator == "prefix") {
            if (!itemValue.toString().startsWith(value)) {
                return false;
            }

        } else if (operator == "suffix") {
            if (!itemValue.toString().endsWith(value)) {
                return false;
            }

        } else if (operator == "wildcard") {
            // 将通配符*替换为正则表达式中的.*，并将其他正则元字符进行转义
            const regexPattern = pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1").replace(/\*/g, '.*');

            // 创建正则表达式对象
            const regex = new RegExp(`^${regexPattern}$`);

            // 进行匹配
            let match = regex.test(itemValue);
            if (!match) {
                return false;
            }
        }
    }
    return true;
}


let exportExcel = function (data, filePath) {
// 创建一个工作簿
    const workbook = XLSX.utils.book_new();

// 创建一个工作表
    const worksheet = XLSX.utils.aoa_to_sheet(data);

// 将工作表添加到工作簿

    XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

    // Convert the workbook to a binary buffer
    const excelData = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });

// 生成Excel文件的二进制数据
//     const excelData = XLSX.write(workbook, {bookType: 'xlsx', type: 'binary'});

// 将二进制数据保存到文件
//     function s2ab(s) {
//         const buf = new ArrayBuffer(s.length);
//         const view = new Uint8Array(buf);
//         for (let i = 0; i < s.length; i++) {
//             view[i] = s.charCodeAt(i) & 0xFF;
//         }
//         return buf;
//     }
//
//     const blob = new Blob([s2ab(excelData)], {type: 'application/octet-stream'});


// 选择保存路径
//     const savePath = path.join(app.getPath('desktop'), 'example.xlsx');

    // 将Blob对象保存为文件
    fs.writeFile(filePath, excelData, (err) => {
        if (err) {
            console.error('export xls failed:', err);
        } else {
            console.log(' export xls success:', filePath);
        }
    });

}

// 导出模块函数
module.exports = {
    matchItemList,
    exportExcel,
};
